// 
// XmppAccountCache.cs
// 
// Copyright © 2009 Jiří Zárevúcky <zarevucky.jiri@gmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

using System;
using System.IO;

namespace Galaxium.Protocol.Xmpp
{
	public class XmppAccountCache: AbstractAccountCache
	{
		public XmppAccountCache (IAccount acc, string dir)
			:base (acc, dir)
		{
		}
		
		public override void GetAccountImage ()
		{
		}

		public override void SaveAccountImage (string filename)
		{
			SaveImage (filename);
		}

		public override void SaveAccountImage ()
		{
		}

		public override IDisplayImage GetDisplayImage (IContact contact)
		{
			var filename = Path.Combine (ImagesDirectory, contact.UniqueIdentifier);
			if (!File.Exists (filename)) return null;
			var hash = File.ReadAllText (filename);
			return RetrieveImage (hash);
		}

		public override void SaveDisplayImage (IContact contact)
		{
			if (contact.DisplayImage == null) return;
			SaveImage (contact.DisplayImage);
			File.WriteAllText (Path.Combine (ImagesDirectory, contact.UniqueIdentifier),
			                   contact.DisplayImage.Checksum);
		}
		
		public void SaveImage (IDisplayImage image)
		{
			File.WriteAllBytes (Path.Combine (ImagesDirectory, image.Checksum), image.ImageBuffer);
		}
		
		public void SaveImage (string filename)
		{
			var hash = Library.Utility.Cryptography.Sha1HexHash (File.ReadAllBytes (filename));
			File.Copy (filename, Path.Combine (ImagesDirectory, hash), true);
		}
		
		public void SaveImage (byte[] data)
		{
			var hash = Library.Utility.Cryptography.Sha1HexHash (data);
			File.WriteAllBytes (Path.Combine (ImagesDirectory, hash), data);
		}
		
		public IDisplayImage RetrieveImage (string sha1hash)
		{
			var filename = Path.Combine (ImagesDirectory, sha1hash);
			return File.Exists (filename) ? new XmppDisplayImage (filename) : null;
		}
	}
}
